package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.feign.common.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ItemListener {
    @Autowired
    RestHighLevelClient client;
    //指定从那个队列消费消息
    @RabbitListener(queues = "item.insert.queue")
    public void insertMessage(String msg) throws IOException {
        System.out.println("接收到的消息:"+ msg);
        //将json转换为对象
        Item item = JSON.parseObject(msg, Item.class);
        ItemDoc itemDoc = new ItemDoc();
        BeanUtils.copyProperties(item,itemDoc);
        System.out.println(itemDoc);
        //将数据更新到es中
        IndexRequest request = new IndexRequest("hmall");
        request.id(itemDoc.getId().toString());
        request.source(JSON.toJSONString(itemDoc),XContentType.JSON);
        client.index(request,RequestOptions.DEFAULT);
    }

    //指定从那个队列消费消息
    @RabbitListener(queues = "item.delete.queue")
    public void deleteMessage(String msg) throws IOException {
        System.out.println("接收到的消息:"+ msg);
        DeleteRequest request = new DeleteRequest("hmall");
        request.id(msg);
        client.delete(request,RequestOptions.DEFAULT);
    }
}
